package com.example.myapplication.module1.activity

import android.os.Bundle
import android.view.View
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivityCustomerManagerBinding
import com.example.myapplication.entity.AreaListBean
import com.example.myapplication.entity.DataDictBean
import com.example.myapplication.entity.ItemBean
import com.example.myapplication.module1.dialog.ChooseTypeDialog
import com.example.myapplication.module1.presenter.CustomerManagerPresenter
import com.example.myapplication.soaprequest.SoapEnvelop
import com.example.myapplication.soaprequest.request.*
import com.example.myapplication.widget.CustomerToolbar
import com.example.mylibrary.base.BaseMvpActivity
import com.example.mylibrary.utils.GsonUtil
import com.example.mylibrary.utils.UiTools
import com.google.gson.reflect.TypeToken
import com.lxj.xpopup.impl.LoadingPopupView

/**
 * 客户管理
 */
class CustomerManagerActivity :
    BaseMvpActivity<CustomerManagerActivity, CustomerManagerPresenter, ActivityCustomerManagerBinding>() {
    lateinit var loadPopup: LoadingPopupView
    private var dataDictBeanList: MutableList<DataDictBean>? = mutableListOf()
    private var areaTypeList: MutableList<DataDictBean>? = mutableListOf()
    private var areaList: MutableList<AreaListBean>? = mutableListOf()
    private var areaStringBuffer = StringBuffer()
    private var areaIdBuffer = StringBuffer()
    private var pvTime: TimePickerView? = null
    private var dateType = ""
    private var curPage = 1
    private val areaTypeListRequest = AreaTypeListRequest()
    private val customerManagerListRequest = CustomerManagerListRequest()
    private val areaListRequest = ArealistRequest()
    private val dataDictRequest = DataDictRequest()
    private val soapRequestBody = SoapRequestBody()
    private val soapEnvelop = SoapEnvelop()
    private val typeList = UiTools.getStringArray(R.array.clientType)

    private val chooseTypeDialog: ChooseTypeDialog by lazy {
        ChooseTypeDialog(this)
    }

    override fun getPresenter(): CustomerManagerPresenter = CustomerManagerPresenter()

    override fun getBinding(): ActivityCustomerManagerBinding {
        return ActivityCustomerManagerBinding.inflate(layoutInflater)
    }

    override fun initView() {
        loadPopup = builder.asLoading("加载中...")
        val itemInfo = bundleExtra?.getParcelable<ItemBean>("itemInfo")
        viewBinding.clToolbar.setTitle(itemInfo?.itemName)
        viewBinding.clToolbar.clickListener = object : CustomerToolbar.ClickListener {
            override fun onBackListener() {
                finish()
            }

            override fun onRightListener() {
                finish()
            }
        }
        // 设置默认为客户
        viewBinding.tvClient.text = typeList[1]
        viewBinding.tvClient.hint = "1"

        // 客户类型选择点击回调
        chooseTypeDialog.confirmListener = object : ChooseTypeDialog.ConfirmListener {
            override fun onConfirmListener(position: Int, type: String) {
                // 全部和员工不显示等级
                if (position != 0 && position != 5) {
                    viewBinding.groupLevel.visibility = View.VISIBLE
                } else {
                    viewBinding.groupLevel.visibility = View.GONE
                    viewBinding.tvClientLevel.text = ""
                    viewBinding.tvClientLevel.hint = ""
                }
                if (viewBinding.tvClient.hint != "$position") {
                    viewBinding.tvClient.text = type
                    viewBinding.tvClient.hint = "$position"
                    viewBinding.tvClientLevel.text = ""
                    viewBinding.tvClientLevel.hint = ""
                }
            }
        }
        // 等级点击回调
        chooseTypeDialog.dataDictChooseListener = object : ChooseTypeDialog.DataDictChooseListener {
            override fun onConfirmListener(dataDictBean: DataDictBean) {
                when (dataDictRequest.zdbm) {
                    UiTools.getString(R.string.XMGM) -> {
                        // 拜访阶段选择结果
                        viewBinding.tv22.text = dataDictBean.dictmc
                        viewBinding.tv22.hint = dataDictBean.id
                    }
                    else -> {
                        // 等级选择结果
                        viewBinding.tvClientLevel.text = dataDictBean.dictmc
                        viewBinding.tvClientLevel.hint = dataDictBean.id
                    }
                }
            }
        }

        // 区域点击回调
        chooseTypeDialog.areaTypeChooseListener = object : ChooseTypeDialog.AreaTypeChooseListener {
            override fun onConfirmListener(dataDictBean: DataDictBean) {
                // 区域
                viewBinding.tvClientAreaType.text = dataDictBean.dictmc
                viewBinding.tvClientLevel.hint = dataDictBean.id
            }
        }

        chooseTypeDialog.areaListChooseListener = object : ChooseTypeDialog.AreaListChooseListener {
            override fun onConfirmListener(areaList: AreaListBean, level: String) {
                areaStringBuffer.append("${areaList.cname}-")
                areaIdBuffer.append("${areaList.id}-")
                when (level) {
                    "1" -> {
                        // 国家
//                        getArea("3","1")
                    }
                    "2" -> {
                        // 省
                        getArea("3", areaList.id)
                    }
                    "3" -> {
                        // 市
                        getArea("4", areaList.id)
                    }
                    "4" -> {
                        // 区名称
                        viewBinding.tvClientArea.text =
                            areaStringBuffer.substring(0, areaStringBuffer.length - 1).toString()
                        // 地区id
                        viewBinding.tvClientArea.hint =
                            areaIdBuffer.substring(0, areaIdBuffer.length - 1).toString()
                    }
                }
            }
        }
        // 拜访阶段选择按钮
        viewBinding.cbVisitStage.setOnCheckedChangeListener { buttonView, isChecked ->
            viewBinding.tv22.isEnabled = isChecked
        }
        // 按是否拜访
        viewBinding.cbByVisit.setOnCheckedChangeListener { buttonView, isChecked ->
            viewBinding.rbNoVisit.isEnabled = isChecked
            viewBinding.rbYesVisit.isEnabled = isChecked
        }

        //时间选择器
        pvTime = TimePickerBuilder(this) { date, _ ->
            when (dateType) {
                "1" -> {
                    viewBinding.tvStartTime.text = UiTools.formatDate(date, "yyyy-MM-dd")
                }
                "2" -> {
                    viewBinding.tvEndTime.text = UiTools.formatDate(date, "yyyy-MM-dd")
                }
            }

        }
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .build()

        viewBinding.tvClient.setOnClickListener(this)
        viewBinding.tvClientLevel.setOnClickListener(this)
        viewBinding.tvClientAreaType.setOnClickListener(this)
        viewBinding.tvClientArea.setOnClickListener(this)
        viewBinding.tv22.setOnClickListener(this)
        viewBinding.tvStartTime.setOnClickListener(this)
        viewBinding.tvEndTime.setOnClickListener(this)
        viewBinding.tvSearch.setOnClickListener(this)
        viewBinding.tvNewClient.setOnClickListener(this)
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tvClient -> {
                // 客户类型
                chooseTypeDialog.getDialog(typeList.toMutableList())
            }
            R.id.tvClientLevel -> {
                // 客户等级
                getLevel()
            }
            R.id.tvClientAreaType -> {
                // 客户区域
                getClientArea()
            }
            R.id.tvClientArea -> {
                // 客户地区
                areaStringBuffer.setLength(0)
                areaIdBuffer.setLength(0)
                getArea("2", "0")
            }
            R.id.tv22 -> {
                // 拜访阶段
                getVisitStage()
            }
            R.id.tvStartTime -> {
                // 开始日期
                dateType = "1"
                pvTime?.show()
            }
            R.id.tvEndTime -> {
                // 结束日期
                dateType = "2"
                pvTime?.show()
            }
            R.id.tvSearch -> {
                // 查询
                customerManagerListRequest.types = (viewBinding.tvClient.hint ?: "").toString()
                customerManagerListRequest.dwmc = viewBinding.etClientUnit.text.toString()
                customerManagerListRequest.lxrname = viewBinding.etContact.text.toString()
                customerManagerListRequest.phone = viewBinding.etPhone.text.toString()
                customerManagerListRequest.qq = viewBinding.etQQ.text.toString()
                customerManagerListRequest.xmjd = (viewBinding.tv22.hint ?: "").toString()

                if (viewBinding.cbByVisit.isChecked) {
                    if (viewBinding.rbNoVisit.isChecked) {
                        customerManagerListRequest.zt = "0"
                    }
                    if (viewBinding.rbYesVisit.isChecked) {
                        customerManagerListRequest.zt = "1"
                    }
                } else {
                    customerManagerListRequest.zt = "-1"
                }
                customerManagerListRequest.qsrq = viewBinding.tvStartTime.text.toString()
                customerManagerListRequest.zzrq = (viewBinding.tvEndTime.hint ?: "").toString()
                customerManagerListRequest.typeid =
                    (viewBinding.tvClientLevel.hint ?: "").toString()
                customerManagerListRequest.areaid =
                    (viewBinding.tvClientAreaType.hint ?: "").toString()

                if (!viewBinding.tvClientArea.hint.isNullOrEmpty()) {
                    val split = (viewBinding.tvClientArea.hint ?: "").toString().split("-")
                    customerManagerListRequest.cityid = split[0]
                    customerManagerListRequest.countyid = split[1]
                    customerManagerListRequest.areatypeid = split[2]
                }
                customerManagerListRequest.curpage = "$curPage"

                val bundle = Bundle()
                bundle.putParcelable("customerManagerListRequest", customerManagerListRequest)
                startNextActivity(this, bundle, CustomerManagerListActivity::class.java)
            }
            R.id.tvNewClient -> {
                // 新增单位

            }
        }
    }

    private fun getLevel() {
        when (viewBinding.tvClient.hint) {
            "1" -> {
                // 客户
                dataDictRequest.zdbm = UiTools.getString(R.string.KHDJ)
            }
            "2" -> {
                // 供应商
                dataDictRequest.zdbm = UiTools.getString(R.string.GYSDJ)
            }
            "3" -> {
                // 竞争对手
                dataDictRequest.zdbm = UiTools.getString(R.string.DSDJ)
            }
            "4" -> {
                // 渠道
                dataDictRequest.zdbm = UiTools.getString(R.string.KHDJ)
            }
            "6" -> {
                // 物流
                dataDictRequest.zdbm = UiTools.getString(R.string.WLDJ)
            }
        }

        soapRequestBody.value = dataDictRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getDataDict(soapEnvelop)
    }

    private fun getClientArea() {
        soapRequestBody.value = areaTypeListRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getAreaType(soapEnvelop)
    }

    private fun getArea(level: String, parentid: String) {
        areaListRequest.levels = level
        areaListRequest.parentid = parentid
        soapRequestBody.value = areaListRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getAreaList(soapEnvelop)
    }


    private fun getVisitStage() {
        // 拜访阶段
        dataDictRequest.zdbm = UiTools.getString(R.string.XMGM)
        soapRequestBody.value = dataDictRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getDataDict(soapEnvelop)
    }

    override fun initData() {


    }

    fun showLoad() {
        loadPopup.show()
    }

    fun dismissLoad() {
        loadPopup.dismiss()
    }


    fun setDataDict(result: String) {
        dataDictBeanList = GsonUtil.fromJson<MutableList<DataDictBean>>(
            result,
            object : TypeToken<MutableList<DataDictBean>>() {}.type
        )
        if (dataDictBeanList.isNullOrEmpty()) {
            UiTools.showToast(getString(R.string.noData1))
        } else {
            when (dataDictRequest.zdbm) {
                UiTools.getString(R.string.XMGM) -> {
                    // 项目进度(拜访阶段)
                    dataDictBeanList?.add(DataDictBean("-1", getString(R.string.all)))
                }
                else -> {
                    dataDictBeanList?.add(DataDictBean("0", getString(R.string.all)))
                }
            }
            chooseTypeDialog.getDataDialog(dataDictBeanList)
        }
    }

    fun setAreaType(result: String) {
        areaTypeList = GsonUtil.fromJson<MutableList<DataDictBean>>(
            result,
            object : TypeToken<MutableList<DataDictBean>>() {}.type
        )
        if (areaTypeList.isNullOrEmpty()) {
            UiTools.showToast(getString(R.string.noData1))
        } else {
            chooseTypeDialog.getAreaTypeDialog(dataDictBeanList)
        }
    }

    fun setAreaList(result: String) {
        areaList = GsonUtil.fromJson<MutableList<AreaListBean>>(
            result,
            object : TypeToken<MutableList<AreaListBean>>() {}.type
        )
        if (areaList.isNullOrEmpty()) {
            UiTools.showToast(getString(R.string.noData1))
        } else {
            AreaListBean("0", getString(R.string.all))
            chooseTypeDialog.getAreaListDialog(areaList, areaListRequest.levels)
        }
    }

}
